package com.weiiew.backend.controller;

import com.weiiew.backend.entity.config.ScriptConfig;
import com.weiiew.backend.entity.enums.ExecutorState;
import com.weiiew.backend.executor.ScriptExecutor;
import com.weiiew.backend.operationUtils.OperationSequence;
import com.weiiew.backend.utils.ApiResponse;
import com.weiiew.backend.utils.ScriptManager;
import com.weiiew.backend.utils.listener.HotkeyListenerManager;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * @author 魏锴
 * @since 2025/4/30
 */
@RestController
@RequestMapping("/script")
@RequiredArgsConstructor
public class ScriptRunController {
    // 操作执行器
    private final ScriptExecutor executor;
    private final ScriptManager scriptManager;
    private final HotkeyListenerManager manager;
    private final ScriptConfig config = new ScriptConfig();

    /**
     * 脚本运行页面绑定
     *
     * @return 绑定结果
     */
    @RequestMapping("/run/bind")
    public ApiResponse runBind(String path) throws IOException {
        // 执行操作队列
        OperationSequence sequence = scriptManager.loadScript(path);
        config.setChannel("/topic/script-run-message");
        config.setSequence(sequence);
        manager.registerHotkey("script.run.toggle", () -> executor.toggle(config));
        return ApiResponse.ok();
    }

    /**
     * 脚本运行页面解绑
     *
     * @return 绑定结果
     */
    @RequestMapping("/run/unbind")
    public ApiResponse runUnbind() {
        manager.unregisterHotkey("script.run.toggle");
        ExecutorState state = executor.getState();
        if (state == ExecutorState.RUNNING || state == ExecutorState.PAUSE || state == ExecutorState.COUNTDOWN)
            executor.stop();
        return ApiResponse.ok("解绑成功");
    }

    @PostMapping("/run/list")
    public ApiResponse getRunList() {
        OperationSequence sequence = config.getSequence();
        if (sequence == null) return ApiResponse.failure("未绑定脚本");
        else if (sequence.getOperations().isEmpty()) return ApiResponse.failure("脚本中无操作");
        else return ApiResponse.ok("绑定成功")
                    .append("name", sequence.getName())
                    .append("time", sequence.getExecutorTime())
                    .append("list", sequence.getOperations());
    }

    /**
     * 页面脚本运行状态切换
     *
     * @return 切换结果
     */
    @PostMapping("/run/toggle")
    public ApiResponse toggle() {
        executor.toggle(config);
        return ApiResponse.ok("切换成功");
    }

    /**
     * 重置脚本执行状态
     *
     * @return 重置结果
     */
    @PostMapping("/run/reset")
    public ApiResponse reset() {
        executor.reset();
        return ApiResponse.ok("重置成功");
    }
}
